<template>
  <div class="h-full flex flex-col">
    <div class="topTitle">{{ $t( 'dco.portal.task') }}</div>
    <div class="mt-2 flex w-full h-80 bg-white" v-show="Pa">
      <div style="position: relative;width: 70%;">
        <div class="review">
          <div class="text">{{ $t('dco.portal.sum') }}</div>
          <div class="numType" @click="clickButton(1, '2,3,4,-1')">{{ reviewTotal }}</div>
          <div class="numTotal">
            <div class="zhu"></div>
            <div class="textBox">
              <div style="font-size: 16px;">DPIA</div>
              <div style="font-size: 36px;cursor: pointer;" @click="clickButton(1, '2,3,4,-1')">{{ totalDpia }}</div>
            </div>
          </div>
        </div>
        <div style="margin: -74px 0 0px 200px;">
          <div class="echart" id="byrsBar" :style="{ width: '100%', height: '100px' }"></div>
        </div>
      </div>
      <div style="position: relative;border-left: 1px solid #D3D3D3;margin: 25px 0;">
        <div class="review1">
          <div class="text">{{ $t('dco.portal.change.opinions') }}</div>
          <div class="numType" @click="clickButton(2,'')">{{ exchangeOpinions }}</div>
          <div class="numTotal1 numTotal2">
            <div class="zhu zhu1"></div>
            <div class="textBox">
              <div style="font-size: 16px;">{{ $t('dco.portal.status5') }}</div>
              <div style="font-size: 36px;cursor: pointer;" @click="clickButton(2,'1')">{{ completed }}</div>
            </div>
          </div>
          <div class="numTotal1">
            <div class="zhu zhu2"></div>
            <div class="textBox textBox1">
              <div style="font-size: 16px;width: 100px;">{{ $t('dco.portal.status6') }}</div>
              <div style="font-size: 36px;cursor: pointer;width: 100px;" @click="clickButton(2,'0')">{{ unprocessed }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <a-card class="mt-[10px]">
      <div style="display: flex;margin-bottom: 20px;">
        <a-button type="link" :class="isLable === 1 ? 'active' : ''" class="button-text" @click="clickButton(1, '')">{{
          $t('dco.portal.table.btn1') }}     
          (<span> {{ pagination.total }} </span> )
        </a-button>
        <a-button type="link" :class="isLable === 2 ? 'active' : ''" class="button-text" @click="clickButton(2, '')">{{
          $t('dco.portal.table.btn2') }}
           (<span>{{  pagination2.total }}</span> ) 
        </a-button>
        
        <a-button v-if="riskTotal > 0" type="link" :class="isLable === 3 ? 'active' : ''" class="button-text" @click="clickButton2">{{
          $t('dco.portal.table.btn3') }}
           (<span>{{ riskTotal }}</span> )
        </a-button>

      </div>
      <div class="Pa" @click="showPa"></div>

      <creatRiskAction :mode="mode" :riskId="riskId" :editId="editId" 
      ref="creatRiskAction" @getList="getList" @succeed="succeed">
      </creatRiskAction>

      <!-- 主列表dpia -->
      <a-table v-if="showDpia" ref="table" size="middle" class="h-full overflow-x-auto" 
        :dataSource="listData"
        :pagination="false" @change="tableChange" :loading="listLoading" :rowKey="(record) => record.Id" @expand="getRiskList"
				:expanded-row-keys.sync="expandedRowKeys"
        :locale="lang === 'zh-EN' ? customLocale1 : customLocale2">

        <!-- +号 -->
        <template slot="expandedRowRender" slot-scope="precord, text">
          <a-table :pagination="false" size="middle" style="margin-top: 20px" class="h-full overflow-x-auto"
            :dataSource="riskList" :rowKey="(record) => record.Id">
            <!-- Action Name -->
            <a-table-column key="DpiaActionName" width="150px" :customRender="(_, record) => {
                return record.DpiaActionName || record.DpiaActionIdTag;
              }
              ">
              <span slot="title">{{
                $t("user.verification-code.required111566166")
              }}</span>
            </a-table-column>
            <!-- Source -->
            <a-table-column key="DpiaActionSource" data-index="DpiaActionSource" width="150">
              <span slot="title">{{
                $t("user.verification-code.required111566167")
              }}</span>
            </a-table-column>
            <!-- Action Result -->
            <a-table-column key="DpiaActionResult" data-index="DpiaActionResult" width="150">
              <span slot="title">{{
                $t("user.verification-code.required1115661688888")
              }}</span>
            </a-table-column>
            <!-- Action Owner -->
            <a-table-column
              key="DpiaActionUserResponsible"
              data-index="DpiaActionUserResponsible"
              width="150"
            >
              <span slot="title">{{
                $t("user.verification-code.required1115661281111")
              }}</span>
            </a-table-column>
            <!-- Creation Time -->
            <a-table-column
              key="DpiaActionCreatetime"
              data-index="DpiaActionCreatetime"
              width="150"
            >
              <span slot="title">{{
                $t("user.verification-code.required111566169")
              }}</span>
            </a-table-column>
            <!-- Due Date -->
            <a-table-column
              key="DpiaActionFinishTime"
              data-index="DpiaActionFinishTime"
              width="150"
            >
              <span slot="title">{{
                $t("user.verification-code.required111566170")
              }}</span>
            </a-table-column>
            <!-- 状态 -->
            <a-table-column
              key="DpiaActionStatus"
              :title="$t('user.login.message-invalid-verification-code0011')"
            >
              <template slot-scope="text, record">
                <span>
                  <div v-if="record.DpiaActionStatus == 1">
                    <a-badge color="blue" />
                    {{ $t("user.verification-code.required111566133") }}
                  </div>
                  <div v-else-if="record.DpiaActionStatus == 3">
                    <a-badge color="purple" />
                    {{ $t("user.verification-code.required1115661455555") }}
                  </div>
                  <div v-else-if="record.DpiaActionStatus == 4">
                    <a-badge color="green" />
                    {{ $t("user.verification-code.required111566146") }}
                  </div>
                  <div v-else-if="record.DpiaActionStatus == 5">
                    <a-badge color="grey" />
                    {{
                      $t(
                        "user.verification-code.required111566110577371442281431222335566555555"
                      )
                    }}
                  </div>
                </span>
              </template>
            </a-table-column>
            <a-table-column
              key="action"
              :title="$t('app.setting.othersettings')"
              style="margin-left: -15px"
            >
              <template slot-scope="text, record">
                <span>
                  <a-space size="0">
                    <!-- 修改按钮 -->
                    <a-button
                      type="link"
                      @click="showModal('1', record.Id, record.state, record)"
                      block>
                      <!-- v-if="
                        ((precord.DpiaDcoUserId === userId ||
                          precord.RiskOwnerUserId === userId) &&
                          (precord.DpiaStatus === 4 ||
                            precord.DpiaStatus === 2 ||
                            precord.DpiaStatus === 3 ||
                            precord.RiskState === 3)) ||
                        (precord.DpiaDcoUserId !== userId &&
                          precord.RiskOwnerUserId !== userId &&
                          record.DpiaActionUserId === userId &&
                          precord.DpiaStatus === 4)
                      " -->
                      {{
                        $t("user.verification-code.required111566147")
                      }}</a-button
                    >
                    <!-- 删除按钮 -->
                    <a-popconfirm :title="
                        $t('user.verification-code.required111566110577225')"
                      :ok-text="$t('user.verification-code.required1166')"
                      :cancel-text="$t('user.email.required11')"
                      @confirm="delActions(record.Id)" >
                      <!-- v-if="
                        precord.DpiaDcoUserId &&
                        (precord.DpiaDcoUserId === userId ||
                          precord.DpiaDcoUserId === RiskOwnerUserId) &&
                        (precord.DpiaStatus === 2 ||
                          precord.DpiaStatus === 3 ||
                          precord.RiskState === 2 ||
                          precord.RiskState === 3)
                      " -->
                   
                      <a-button type="link" v-if="!bianjike">{{
                        $t("menu.exception.trigger")
                      }}</a-button>
                    </a-popconfirm>
                  </a-space>
                </span>
              </template>
            </a-table-column>
          </a-table>
        </template>

        <!--Type----------------------->
        <a-table-column key="type" data-index="type" width="180px"
          @filterDropdownVisibleChange="(e) => { if (e) this.setValus(1) }">
          <span slot="title">{{ $t("dco.portal.table.column1") }}</span>
          <span slot="filterDropdown" slot-scope="{
							setSelectedKeys,
							selectedKeys,
							confirm,
							clearFilters,
							column,
						}">
            <table-select ref="tableselect1" :filter-data="filterData" :single-search="false"
              @searchFilter="searchQueryFilter" @searchClose="confirm" @searchClean="tableCleanJobs" />
          </span>
          <template slot-scope="text, record">
            <span>{{ record.DpiaId }}</span>
          </template>
        </a-table-column>
        <!-- Name------------------- -->
        <a-table-column key="DpiaName" data-index="DpiaName"
          @filterDropdownVisibleChange="(e) => { if (e) this.setValus(2) }">
          <span slot="title">{{ $t("dco.portal.table.column2") }}</span>
          <span slot="filterDropdown" slot-scope="{
							setSelectedKeys,
							selectedKeys,
							confirm,
							clearFilters,
							column,
						}">
            <table-select ref="tableselect2" :filter-data="filterData" @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter" @searchClose="confirm" @searchClean="tableCleanJobs" />
          </span>
          <template slot-scope="text, record">
            <span>{{
              record.DpiaName
            }}</span>
          </template>
        </a-table-column>
        <!-- 状态------------------------->
        <a-table-column key="DpiaStatus" data-index="DpiaStatus" width="160px"
          @filterDropdownVisibleChange="(e) => { if (e) this.setValus(3) }">
          <span slot="title">{{
            $t("dco.portal.table.column3")
          }}</span>
          <span slot="filterDropdown" slot-scope="{
							setSelectedKeys,
							selectedKeys,
							confirm,
							clearFilters,
							column,
						}">
            <table-select ref="tableselect3" :single-search="false" :filter-data="filterData" @searchClose="confirm"
              @searchClean="tableCleanJobs" @searchFilter="searchQueryFilter" />
          </span>
          <template slot-scope="text, record">
            <a-popover>
              <template slot="content">
                <a-timeline>
                  <a-timeline-item v-if="isLable === 1" v-for="item in caogao" :key="item.value" :class="{
                    'timeline-item-green':
                      item.value < record.DpiaStatus,
                    'timeline-item-red':
                      item.value == record.DpiaStatus,
                    'timeline-item-gray':
                      item.value > record.DpiaStatus,
                  }">
                    {{ $t(item.label) }}
                  </a-timeline-item>
                  <a-timeline-item v-if="isLable === 2" v-for="item in caogao1" :key="item.value" :class="{
                    'timeline-item-green':
                      item.value < record.DpiaStatus,
                    'timeline-item-red':
                      item.value == record.DpiaStatus,
                    'timeline-item-gray':
                      item.value > record.DpiaStatus,
                  }">
                    {{ $t(item.label) }}
                  </a-timeline-item>
                </a-timeline>
              </template>
              <a-button v-if="isLable === 1" style="border: none">
                <div v-if="record.DpiaStatus == -1">
                  <a-badge color="blue" />
                  {{
                    $t(
                      'user.verification-code.required111566133.returned'
                    )
                  }}
                </div>
                <div v-else-if="record.DpiaStatus == 2">
                  <a-badge color="orange" />
                  {{
                    $t(
                      'user.verification-code.required1115661444444'
                    )
                  }}
                </div>
                <div v-else-if="record.DpiaStatus == 3">
                  <a-badge color="purple" />
                  {{
                    $t(
                      'user.verification-code.required1115661105716'
                    )
                  }}
                </div>
                <div v-else-if="record.DpiaStatus == 4">
                  <a-badge color="green" />
                  {{
                    $t(
                      'user.verification-code.required111566146'
                    )
                  }}
                </div>
                <div v-else-if="record.DpiaStatus == 5">
                  <a-badge color="red" />
                  {{
                    $t(
                      'user.verification-code.required11156614611'
                    )
                  }}
                </div>
              </a-button>
              <a-button v-if="isLable === 2" style="border: none">
                <div v-if="record.DpiaStatus == 0">
                  <a-badge color="red" />
                  {{
                    $t(
                      'user.verification-code.no'
                    )
                  }}
                </div>
                <div v-else-if="record.DpiaStatus == 1">
                  <a-badge color="green" />
                  {{
                    $t('user.verification-code.yes')
                  }}
                </div>
              </a-button>
            </a-popover>
          </template>

        </a-table-column>
        <!-- RPA_ID------------------- -->
        <a-table-column key="RpaId" data-index="RpaId" width="140px"
          @filterDropdownVisibleChange="(e) => { if (e) this.setValus(4) }">
          <span slot="title">{{
            $t("dco.portal.table.column4")
          }}</span>
          <span slot="filterDropdown" slot-scope="{
							setSelectedKeys,
							selectedKeys,
							confirm,
							clearFilters,
							column,
						}">
            <table-select ref="tableselect4" :filter-data="filterData" @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter" @searchClose="confirm" @searchClean="tableCleanJobs" />
          </span>
          <template slot-scope="record">
            <rpaDetail :rpaDetailId="record" />
          </template>
        </a-table-column>
        <!--DI 细节------------------- -->
        <a-table-column key="DIDetails" data-index="DIDetails" width="140px"
          @filterDropdownVisibleChange="(e) => { if (e) this.setValus(5) }">
          <span slot="title">{{
            $t("dco.portal.table.column5")
          }}</span>
          <span slot="filterDropdown" slot-scope="{
							setSelectedKeys,
							selectedKeys,
							confirm,
							clearFilters,
							column,
						}">
            <table-select ref="tableselect5" :filter-data="filterData" @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter" @searchClose="confirm" @searchClean="tableCleanJobs" />
          </span>
          <template slot-scope="record">
            <!-- <DIdetail :DIdetailId="record" /> -->
            <!-- 向子组件中传递初始化数据 -->
            <DIdetail :DIdetailId="record" :initData="initData" />
          </template>
        </a-table-column>
        <!-- 风险评估------------------- -->
        <!-- <a-table-column key="RiskAssociated" data-index="RiskAssociated" width="180px"
          @filterDropdownVisibleChange="(e) => { if (e) this.setValus(6) }">
          <span slot="title">{{
            $t("dco.portal.table.column6")
          }}</span>
          <span slot="filterDropdown" slot-scope="{
							setSelectedKeys,
							selectedKeys,
							confirm,
							clearFilters,
							column,
						}">
            <table-select ref="tableselect6" :filter-data="filterData" @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter" @searchClose="confirm" @searchClean="tableCleanJobs" />
          </span>
          <template slot-scope="record">
            span @click="goRisk(row)" :style="{ color: record.DPRisk === 'NONE' ? 'black' : '#3784DD' }">
              {{ record.RiskAssociated }}
            </span> 
            <span>
              {{ record.RiskAssociated ? record.RiskAssociated.split(",").join(", ") : "-" }}
            </span>
          </template>
        </a-table-column> -->
        <!-- 创建人------------------- -->
        <a-table-column key="DpiaCreateUserName" data-index="DpiaCreateUserName" width="180px"
          @filterDropdownVisibleChange="(e) => { if (e) this.setValus(7) }">
          <span slot="title">{{
            $t("dco.portal.table.column7")
          }}</span>
          <span slot="filterDropdown" slot-scope="{
							setSelectedKeys,
							selectedKeys,
							confirm,
							clearFilters,
							column,
						}">
            <table-select ref="tableselect7" :filter-data="filterData" :single-search="false"
              @searchFilter="searchQueryFilter" @searchClose="confirm" @searchClean="tableCleanJobs" />
          </span>
          <template slot-scope="record,text">
            {{ text.DpiaCreateUserName }}
          </template>
        </a-table-column>
        <!-- 创建时间------------------- -->
        <a-table-column key="CreateTime" data-index="CreateTime" width="180px"
          @filterDropdownVisibleChange="(e) => { if (e) this.setValus(8) }">
          <span slot="title">{{
            $t("dco.portal.table.column8")
          }}</span>
          <span slot="filterDropdown" slot-scope="{
							setSelectedKeys,
							selectedKeys,
							confirm,
							clearFilters,
							column,
						}">
            <table-select ref="tableselect8" :filter-data="filterData" :single-search="false"
              @searchFilter="searchQueryFilter" @searchClose="confirm" @searchClean="tableCleanJobs" />
          </span>
          <template slot-scope="record,text">
            {{ text.CreateTime }}
          </template>
        </a-table-column>
        <!-- 最后更新时间------------------- -->
        <a-table-column key="UpdateTime" data-index="UpdateTime" width="170px"
          @filterDropdownVisibleChange="(e) => { if (e) this.setValus(9) }">
          <span slot="title">{{
            $t("dco.portal.table.column9")
          }}</span>
          <span slot="filterDropdown" slot-scope="{
							setSelectedKeys,
							selectedKeys,
							confirm,
							clearFilters,
							column,
						}">
            <table-select ref="tableselect9" :filter-data="filterData" :single-search="false"
              @searchFilter="searchQueryFilter" @searchClose="confirm" @searchClean="tableCleanJobs" />
          </span>
          <template slot-scope="record,text">
            {{ text.UpdateTime }}
          </template>
        </a-table-column>
        <!-- 操作 -->
        <a-table-column key="action" :title="$t('menu.exception.not-find')" width="100px" >
          <template slot-scope="text, record">
            <span>
              <a-dropdown>
                <a-button type="link" v-if="record.DpiaStatus !== 5">
                  <a-icon type="more" />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <!-- 去答题按钮 -->
                    <a-menu-item v-if="record.DpiaStatus === 1 &&
                      (record.Role.CREATE == 1 ||
                        record.Role.WRITE == 1 ||
                        record.Role.VIEW == 1)
                      " @click="edit(record)">
                      <a-button type="link">{{
                        $t('user.verification-code.required1115661105717')
                      }}</a-button>
                    </a-menu-item>
                    <!-- 删除按钮 -->
                    <a-menu-item v-if="record.DpiaStatus === 1 &&
                        record.Role.CREATE == 1
                        ">
                      <a-popconfirm :title="$t(
                        'user.verification-code.required111566110577225'
                      )
                        " :ok-text="$t('user.verification-code.required1166')"
                        :cancel-text="$t('user.email.required11')" @confirm="() => delData(record.Id)">
                        <a-button type="link" style="
														width: 100%;
														text-align: left;
													">{{
													  $t(
													    'menu.exception.trigger'
													  )
													}}</a-button>
                      </a-popconfirm>
                    </a-menu-item>
                    <!-- 撤回 -->
                    <a-menu-item v-if="record.IsDcoState == 0 &&
                        record.Role.CREATE == 1 &&
                        record.DpiaStatus == 2 &&
                        (record.DpiaChangeDcoId !=
                          $store.state.user.info
                            .YtId ||
                          record.DpiaChangeDcoId ==
                          '')
                        ">
                      <a-popconfirm :title="$t(
                        'user.verification-code.required11156611057737144228')"
                        :ok-text="$t('user.verification-code.required1166888')" :cancel-text="$t('user.email.required11')"
                        @confirm="() => withdraw(record)">
                        <a-button style="
														width: 100%;
														text-align: left;
													" type="link">{{
													  $t(
													    'user.verification-code.required11156611057737144227'
													  )
													}}</a-button>
                      </a-popconfirm>
                    </a-menu-item>
                    <!-- 下载 -->
                    <a-menu-item >
                      <a-button type="link" v-if="record.Reports === 1 &&
                        record.RpaIfCompletedPIA ===
                        0 &&
                        record.RpaNoPIOrImportantInvolved ==
                        0 &&
                        (record.DpiaChangeDcoId !=
                          $store.state.user.info
                            .YtId ||
                          record.DpiaChangeDcoId ==
                          '')
                        " @click="xiazai(record)">{{
                        $t(
                          'user.verification-code.required1115661105715'
                        )
                      }}</a-button>
                    </a-menu-item>
                    <!-- 查看 -->
                    <a-menu-item v-if="(isLable === 2 &&
                          (record.DpiaStatus === 2 ||
                            record.DpiaStatus ===
                            3)) ||
                        (isLable === 1 &&
                          record.DpiaStatus === 2)
                        " @click="review(record)">
                      <a-button type="link">{{
                        $t(
                          'user.verification-code.required1115661105718'
                        )
                      }}</a-button>
                    </a-menu-item>
                    <!-- 评估 -->
                    <a-menu-item v-if="(record.DpiaStatus === 2 &&
                          record.ReviewStatus ===
                          1) ||
                        record.Role.CHANGE
                        " @click="estimate(record)">
                      <a-button type="link">{{
                        $t(
                          'user.verification-code.required1115661105719'
                        )
                      }}</a-button>
                    </a-menu-item>
                    <!-- 整体评估 -->
                    <a-menu-item v-if="(record.DpiaStatus === 3 &&
                          record.Role.DCO == 1 &&
                          (record.DpiaChangeDcoId !=
                            $store.state.user.info
                              .YtId ||
                            record.DpiaChangeDcoId ==
                            '')) ||
                        record.Reports === 1
                        " @click="record.DpiaStatus === 3 ? overall(record, 'allReview') : overall(record, 'see')">
                      <a-button type="link">{{
                        record.DpiaStatus === 3
                        ? $t(
                          'user.verification-code.required1115661105720'
                        )
                        : $t(
                          'user.verification-code.required1115661105718'
                        )
                      }}</a-button>
                    </a-menu-item>
                    <!-- 终止 -->
                    <a-menu-item v-if="(record.DpiaStatus === 2 ||
                          record.DpiaStatus === 3) &&
                        record.Role.CREATE == 1
                        ">
                      <a-popconfirm :title="$t(
                        'user.verification-code.required111566110577314'
                      )
                        " :ok-text="$t('user.verification-code.required1166')"
                        :cancel-text="$t('user.email.required11')" @confirm="() => stop(record)">
                        <a-button type="link">{{
                          $t(
                            'user.verification-code.required1115661105721'
                          )
                        }}</a-button>
                      </a-popconfirm>
                    </a-menu-item>
                    <!-- 多人答题 -->
                    <a-menu-item v-if="record.DpiaStatus != 5 &&
                        record.Role.CREATE == 1 &&
                        record.DpiaStatus === 1 &&
                        record.RpaIfCompletedPIA == 0 &&
                        record.RpaNoPIOrImportantInvolved ==
                        0
                        " @click="showPermissions(record, 'write')">
                      <a-button type="link">
                        {{ $t('user.v17') }}
                      </a-button>
                    </a-menu-item>
                    <!-- 共享权限 -->
                    <a-menu-item v-if="record.DpiaStatus != 5 &&
                      record.Role.CREATE == 1 &&
                      record.DpiaStatus != 1
                      " @click="showPermissions(record)">
                      <a-button type="link">{{
                        $t(
                          'user.verification-code.required1115661105722'
                        )
                      }}</a-button>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <Permissions ref="Permissions"></Permissions>
            </span>
          </template>
        </a-table-column>
      </a-table>
      <createRisk
        ref="createRisk"
        @succeed="getList"
        @initEditId="initEditId"
        @getList="getList"
        :userList="userList"
        :riskLevel="riskLevel"
        :riskType="riskType"
        :editId="editId"
        :mode="mode"
      />
      <riskReview
        ref="riskReview"
        :userList="userList"
        :riskLevel="riskLevel"
        :riskType="riskType"
        :editId="editId"
      ></riskReview>

      <RiskData v-if="isLable == 3" @update:total="handleUpdateTotal"/>

      <!-- 分页 -->
      <a-pagination v-if="showDpia && isLable == 1" size="small" v-model="pagination.current" :total="pagination.total" hideOnSinglePage
        :pageSize.sync="pagination.pageSize" @change="getList()" />

      <a-pagination v-if="showDpia && isLable == 2" size="small" v-model="pagination2.current" :total="pagination2.total" hideOnSinglePage
        :pageSize.sync="pagination2.pageSize" @change="getList()" />
    </a-card>
  </div>
</template>

<script>
import { quesionFindRpaId, rpaDetail } from '@/api/rpa/form'
import * as echarts from 'echarts';
import RpaDetail from '../rpa/rpaDetails.vue';
import DIdetail from '../DI/DiDetails.vue'
import Permissions from '../../dataAssessment/components/Permissions.vue'
import tableSelect from '@/components/tableSelect/tableSelect.vue'
import RiskData from './riskIndex.vue'
import creatRiskAction from "./creatRiskAction.vue";
import createRisk from "./components/createRisk.vue";
import { riskLists} from "@/api/risk/form";

import { dcoDataList,reviewTotal,exchangeTotal, dcoGroup,} from '@/api/dco';
import { dpiaChangeState,dpiaDelete, DpiaList,dpiaWithdraw, isWithdraw,rickActiondel,dpiaSimpleAction} from '@/api/dpia/form'
import { appIdCreatexl, appidSxq,} from "@/api/appid";
import { RISKEditActionList,ristCreateAction,} from "@/api/risk/form";
export default {
  components: {
    Permissions,
    RpaDetail,
    DIdetail,
    tableSelect,
    RiskData,
    creatRiskAction,
    createRisk,
  },
  data() {
    return {
      Pa: true,
      listLoading: false,
      isLable: 1,
      listData: [],
      riskList: [],
      pagination: {
        current: 1, //当前页
        pageSize: 10, //每页条数
        total: 0, //总条数
        showQuickJumper: true,
        hideOnSinglePage: true,
      },
      pagination2: {
        current: 1, //当前页
        pageSize: 10, //每页条数
        total: 0, //总条数
        showQuickJumper: true,
        hideOnSinglePage: true,
      },
      customRowIndex: -1,
      reviewTotal: '',
      totalDpia: '',
      exchangeOpinions: '',
      completed: '',
      unprocessed: '',
      statisticsStatusDpia: [],
      echart1: null,
      echart2: null,
      echart3: null,
      echart4: null,
      lang: 'zh-EN',
      //搜索筛选合并
      setValusKey: '',
      filterData: [],
      queryForm: {},
      caogao: [
        { label: 'user.verification-code.required111566133.dco', value: -1 },
        {
          label: 'user.verification-code.required1115661444444',
          value: 2,
        },
        {
          label: 'user.verification-code.required1115661105716',
          value: 3,
        },
        { label: 'user.verification-code.required111566146', value: 4 },
        {
          label: 'user.verification-code.required11156614611',
          value: 5,
        },
      ],
      caogao1: [
        { label: 'user.verification-code.no', value: 0 },
        {
          label: 'user.verification-code.yes',
          value: 1,
        },
      ],
      kvMap: [
        '',
        'Type',
        'DpiaName',
        'DpiaStatus',
        'DpiaRpaId',
        'Di',
        'Risk',
        'CreateUser',
        'DpiaCreatetime',
        'UpdateTime',
      ],
      okyMap: [
        '',
        'TypeStr',
        'DpiaNameStr',
        'DpiaStatusStr',
        'DpiaRpaIdStr',
        'DiStr',
        'RiskStr',
        'CreateUserStr',
        '',
        'UpdateTime',
      ],
      DpiaStatus: '',
      dataddd: [],
      /** 定义初始化需求传递给子组件 DIdetail 的数据 */
      initData: {},
      isLang: false,
      customLocale1: {
        emptyText: this.$t(' No data '),
      },
      customLocale2: {
        emptyText: this.$t(' 暂无数据 '),
      },
      showRisk: false,
      showDpia: true,
      riskTotal:0,
      
      expandedRowKeys: [], // 扩展行的行键列表
      mode: "",
      riskId: 0,
      editId: 0,
      expanded1:'',
    }
  },
  created() {
  },
  mounted() {
    this.init()
    this.dIDetailInit()
    // window.addEventListener('setItemEvent', (e) => {
    //   if (e.key == 'lang') {
    //     let lang = JSON.parse(e.value)
    //     if (lang == 'zh-EN') {
    //       this.isLang = false;
    //       this.lang = 'zh-EN'
    //       this.getByrsEcharts()
    //     } else {
    //       this.isLang = true
    //       this.lang = 'zh-CN'
    //       this.getByrsEcharts()
    //     }
    //   }
    // })
		// 	if (localStorage.getItem('lang') == '"zh-CN"') {
    //     this.lang = 'zh-CN'
		// 		this.getByrsEcharts()
		// 	} else if (localStorage.getItem('lang') == '"zh-EN"') {
    //     this.lang = 'zh-EN'
		// 		this.getByrsEcharts()
		// 	}

    this.loadLangFromStorage();
    window.addEventListener('setItemEvent', (e) => {
      if (e.key == 'lang') {
          const lang = JSON.parse(e.value);
          this.updateLanguage(lang);
      }
    });

  },

  methods: {
    updateLanguage(lang) {
      this.lang = lang;
      this.isLang = (lang === 'zh-CN' ? true : false);
      this.getByrsEcharts();
    },

    loadLangFromStorage() {
      const storedLang = localStorage.getItem('lang');
      if (storedLang) {
        this.updateLanguage(JSON.parse(storedLang));
      }
    },

    /**
    * 初始化获取子组件 DIdetail 中的数据
    */
    async dIDetailInit() {
      /** 搜索数据 */
      const { data: appidLists } = await appIdCreatexl({ content: '' });
      /** 列表数据 */
      const { data: sonfigurationItemsContent } = await appidSxq({ state: 3 });
      // 存放地
      const { data: fonfigurationItemsContent } = await appidSxq({ state: 4 });
      this.initData = {
        sonfigurationItemsContent,
        fonfigurationItemsContent,
        appidLists
      }
    },

    async getByrsEcharts() {
      const data = this.statisticsStatusDpia;
      const statesType = [2, 3, -1, 4];
      const seriesData = data.map((value, index) => {
        return {
          value: value,
          statesType: statesType[index],
        };
      });

      // console.log('我是狼',this.lang);
      if (this.lang === 'zh-CN') {
        this.dataddd = ['已提交', '审核中', '返回至请求者', '已完成']
      } else if (this.lang === 'zh-EN') {
        this.dataddd = ['Submitted', 'Under Review', 'Return to Requester', 'Completed']
      }
      var myChart = echarts.init(document.getElementById('byrsBar'));
      myChart.setOption({
        textStyle: {
          fontFamily: "bmwTypeGlobalRegularBold, bmwTypeGlobalRegular",
        },
        // 配置x轴数据、样式、名称
        xAxis: {
          type: 'category',
          data: this.dataddd,
          name: '',
          nameTextStyle: {
            fontWeight: 400,
            fontSize: 14
          },
          axisTick: {
            show: false,//不显示坐标轴刻度线
          },
          axisLine: {
            lineStyle: {
              color: '#E6E6E6',
              width: 1,
            }
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#000'
            },
            interval: 0,
            rotate: 0
          },
          // triggerEvent: true 
        },
        // 配置y轴名称，样式
        yAxis: {
          type: 'value',  // y轴名称
          axisLine: { show: false },//不显示坐标轴
          axisTick: {
            show: false,//不显示坐标轴刻度线
          },
          show: false,
        },
        // y轴数据，每个柱条的名称
        series: [
          {
            type: 'bar', // 类型为柱状图
            data: seriesData,
            dataType: data,
            barWidth: '80%', // 柱条宽度
            itemStyle: {
              color: '#8EB4DE'// 柱子的样式
            },
            label: {
              normal: {
                show: true,
                position: 'top',
                textStyle: {
                  color: '#000',
                },
              },
            },
          }
        ],
      })
      // 随着屏幕大小调节图表
      window.addEventListener('resize', () => {
        myChart.resize()
      })
      myChart.on('click', async (params) => {
        this.isLable = 1
        this.showDpia = true
        this.DpiaStatus = params.data.statesType;
        
        this.listLoading = true
        this.queryForm = {
          ...this.queryForm,
        }
        const { data } = await dcoDataList({
          ...{ page: 1, pageSize: 10, userType: 1 ,DpiaStatus: this.DpiaStatus,},
          ...this.queryForm,
        })
        // 解构赋值
        const { Page, PageSize, Total, Lists } = data
        // 给table赋值
        this.listData = Lists || []
        if(this.isLable = 1){
          // 给分页数据赋值
          this.pagination = {
            current: Page,
            pageSize: PageSize,
            total: Total,
          }
        }
       
        setTimeout(() => {
          this.listLoading = false
        }, 600)
      });
    },
    showPa(e) {
      this.Pa = !this.Pa;
    },
    async init() {
      this.getList()
      try {
        const { data: data1 } = await reviewTotal()
        const { totalDpia, statisticsStatusDpia } = data1
        this.reviewTotal = data1.total
        this.totalDpia = totalDpia
        this.statisticsStatusDpia = Object.values(statisticsStatusDpia)
        this.echart1 = statisticsStatusDpia.submittedNum
        this.echart2 = statisticsStatusDpia.underReviewNum
        this.echart3 = statisticsStatusDpia.requesterNum
        this.echart4 = statisticsStatusDpia.completedNum
        this.$nextTick(() => {
          this.getByrsEcharts()
        })
        const { data: data2 } = await exchangeTotal()
        const { completedNum, total, unCompletedNum } = data2
        this.exchangeOpinions = total
        this.completed = completedNum
        this.unprocessed = unCompletedNum

        const { data } = await riskLists({pageType:1 })
        this.riskTotal = data.Total

        const { data:dataList2} = await dcoDataList({
          ...{ page: 1, pageSize: 10, userType: 2, DpiaStatus: '' },
          ...this.queryForm,
        })
        this.pagination2.total = dataList2.Total

      } catch (error) {
        console.log('error:', error)
        this.$message.error(error)
      }
    },
    async getList(state) {
      this.listData = []
      this.listLoading = true
      const currentPagination = this.isLable === 1 ? this.pagination : this.pagination2; 
      // const { current, pageSize } = this.pagination
      const { current, pageSize } = currentPagination;
      try {
        if (state == 'filter') {
          // 调用查询列表
          const { data } = await dcoDataList({
            ...{ page: 1, pageSize: 10, userType: this.isLable, DpiaStatus: this.DpiaStatus },
            ...this.queryForm,
          })

          // 解构赋值
          const { Page, PageSize, Total, Lists } = data
          // 给table赋值
          this.listData = Lists || []

            //  // 给分页数据赋值
            //  this.pagination = {
            //   current: Page,
            //   pageSize: PageSize,
            //   total: Total,
            // }

          if (this.isLable === 1) {
             // 给分页数据赋值
            this.pagination = {
              current: Page,
              pageSize: PageSize,
              total: Total,
            }
          }else if (this.isLable === 2) {
            this.pagination2 = {
              current: Page,
              pageSize: PageSize,
              total: Total,
            }
          }

        } else {
          // 调用查询列表
          const { data } = await dcoDataList({
            ...{ page: current, pageSize, userType: this.isLable, DpiaStatus: this.DpiaStatus },
            ...this.queryForm,
          })
          
          // 解构赋值
          const { Page, PageSize, Total, Lists } = data
          // 给table赋值
          this.listData = Lists || []
          // 给分页数据赋值
          // this.pagination = {
          //   current: Page,
          //   pageSize: PageSize,
          //   total: Total,
          // }
          if (this.isLable === 1) {
             // 给分页数据赋值
            this.pagination = {
              current: Page,
              pageSize: PageSize,
              total: Total,
            }
          }else if (this.isLable === 2) {
            this.pagination2 = {
              current: Page,
              pageSize: PageSize,
              total: Total,
            }
          }
        }
      } catch (error) {
        // 报错信息
        this.$message.error(error)
        console.log(error)
      } finally {
        // 不管成功失败都会执行
        this.listLoading = false
      }
    },

    handleUpdateTotal(newTotal) {
    this.riskTotal = newTotal
  },

    async clickButton(isLable,DpiaStatus) {
      this.isLable = isLable;
      this.DpiaStatus = DpiaStatus;
      this.showDpia = true
      this.showRisk = false
      this.queryForm = {}
      this.getList('filter')
    },
 
    async clickButton2() {
      this.isLable = 3;
      this.showRisk = true
      this.showDpia = false
    },
    // 去答题
    edit(record) {
      this.$router.push({
        path: '/dcoPortal/dcoQuestionnaire',
        query: { id: record.Id },
      })
    },
    /**
     * 删除 通用的
     * @param {*} key
     */
    async delData(id) {
      try {
        // 传过来的id直接请求删除api
        await dpiaDelete({ Id: id })
        this.$message.success(
          this.$t('user.verification-code.required111566110577210')
        )
        // 重新初始化列表刷新数据
        this.init()
      } catch (error) {
        this.$message.error(error)
      } finally {
      }
    },
    //撤回
    async withdraw(e) {
      try {
        console.log(e)
        await dpiaWithdraw({ Id: e.Id })
        this.init()
      } catch (err) {
        this.$message.error(err)
        console.log(err)
      }
    },
    cancel(e) {
      console.log(e)
      this.$message.warning(
        this.$t('user.verification-code.required111566110577313')
      )
    },
    // 答题后的查看
    review(record) {
      this.$router.push({
        path: '/dcoPortal/dcoReview',
        query: { id: record.Id },
      })
    },
    // 评估
    async estimate(record) {
      const res = await isWithdraw({ Id: record.Id })
      // console.log(res)
      if (res.data == 0) {
        this.$message.error('不可评估')
        return
      }
      // DCO评估
      this.$router.push({
        path: '/dcoPortal/estimate',
        query: {
          ...record,
          id: record.Id,
          DpiaCreateUserId: record.DpiaCreateUserId,
          DpiaChangeDcoId: record.DpiaChangeDcoId || '',
          DpiaId: record.DpiaId,
          ChangeCommit: record.Role.CHANGE,
          ifDco: record.Role.DCO,
          isLable: this.isLable,
        },
      })
      localStorage.setItem('ifchaning', true)
    },
    // 整体评估
    overall(record, state) {
      this.$router.push({
        path: '/dcoPortal/overall',
        query: { id: record.Id, state: state, isLable: this.isLable },
      })
    },
    //终止
    async stop(record) {
      await dpiaChangeState({ Id: record.Id, DpiaStatus: 5 })
      this.getList()
    },
    // 多人答题、共享权限
    showPermissions(data, state) {
      //展开可读权限
      this.$refs.Permissions.open(data, state)
    },
    //预览列表
    async xiazai(record) {
      // console.log(record,'record');
      const { data } = await DpiaList({ Id: record.Id })
      const urls = data.Lists.map((item) => item.DpiaReportAddress)
      // console.log(urls);
      if (this.lang === 'zh-EN') {
        const enUrls = urls.filter((url) => url.includes('en'))
        sessionStorage.setItem('report', enUrls)
        this.$router.push({
          path: '/dcoPortal/report',
        })
      } else {
        const cnUrls = urls.filter((url) => !url.includes('en'))
        sessionStorage.setItem('report', cnUrls)
        this.$router.push({
          path: '/dcoPortal/report',
        })
      }
    },

    // 查询Filter逻辑
    async setValus(typeId) {
      // console.log('typeId', typeId);
      this.listLoading = true
      try {
        // 调用查询列表
        const { data } = await dcoGroup({ Condition: typeId, userType: this.isLable })
        // console.log('data0', data);
        // 赋值类型，用于筛选、搜索的直接调用
        // 为了使中文状态下还是中文
        if (this.isLable === 1) {
          for (let j = 0; j < data.length; j++) {
            if (typeId === 3) {
              switch (data[j].value) {
                case 1:
                  data[j].text = this.$t(
                    'user.verification-code.required111566133.dco'
                  )
                  break
                case 2:
                  data[j].text = this.$t(
                    'user.verification-code.required1115661444444'
                  )
                  break
                case 3:
                  data[j].text = this.$t(
                    'user.verification-code.required111566145'
                  )
                  break
                case 4:
                  data[j].text = this.$t(
                    'user.verification-code.required111566146'
                  )
                  break
                case 5:
                  data[j].text = `${this.$t(
                    'user.verification-code.required11156611057737144228143122233556655'
                  )}`
                  break
                default:
                  break
              }
            }
          }
        } else if (this.isLable === 2) {
          for (let j = 0; j < data.length; j++) {
            if (typeId === 3) {
              switch (data[j].value) {
                case '0':
                  data[j].text = this.$t(
                    'user.verification-code.no'
                  )
                  break
                case '1':
                  data[j].text = this.$t(
                    'user.verification-code.yes'
                  )
                  break
                default:
                  break
              }
            }
          }
        }
        this.setValusKey = typeId
        // if (typeId === 9) {
        //   for (let i = 0; i < data.length; i++) {
        //     data[i].text = data[i].textEn
        //   }
        // }
        // 决定中文状态下是英文
        // 赋值筛选的列表，直接赋值
        this.filterData = data
      } catch (error) {
        // 报错信2
        this.$message.error(error)
        console.log(error)
      } finally {
        // 不管成功失败都会执行
        this.listLoading = false
      }
    },
    /**
     * 清空查询数据，并且执行查询
     * @returns {Promise<void>}
     */
    async tableCleanJobs(type) {
      // console.log('清空查询数据，并且执行查询')
      this.pagination.page = 1
      if (type === 'part') {
        this.queryForm[this.kvMap[this.setValusKey]] = undefined
        this.queryForm[this.okyMap[this.setValusKey]] = undefined
      } else {
        this.queryForm = {}
        for (let i = 1; i <= 8; i++) {
          let dom = this.$refs[`tableselect${i}`]
          if (dom) {
            dom.inputValue = ''
            dom.inputCheckValue = []
          }
        }
      }
      this.inputValue = ''
      this.getList()
    },

    /**
     * 列表搜索查询
     * @param e 搜索的值
     * @returns {Promise<void>}
     */
    async searchQuery(e) {
      this.queryForm[this.kvMap[this.setValusKey]] = undefined
      this.queryForm = {
        ...this.queryForm,
        [this.okyMap[this.setValusKey]]: e,
      }
      await this.getList('filter')
    },

    /**
     * 列表筛选查询
     * @param e 筛选的值
     * @returns {Promise<void>}
     */
    async searchQueryFilter(e) {
      this.queryForm[this.okyMap[this.setValusKey]] = undefined
      console.log('this.okyMap', this.setValusKey)
      this.queryForm = {
        ...this.queryForm,
        [this.kvMap[this.setValusKey]]:
          this.setValusKey === 2 ? e.replaceAll('/', '#@%$') : e,
      }
      await this.getList('filter')
    },

    // 分页事件 直接复制使用 通用的
    // tableChange(pagination) {
    //   this.pagination = pagination;
    //   this.getList();
    // },
    // action
    async succeed() {
      this.listData = []
      const { current, pageSize } = this.pagination
      const { data } = await dcoDataList({
        ...{ page: current, pageSize, userType: this.isLable, DpiaStatus: this.DpiaStatus },
        ...this.queryForm,
      })
      
      // 解构赋值
      const { Page, PageSize, Total, Lists } = data
      // 给table赋值
      this.listData = Lists || []
      // 给分页数据赋值
      this.pagination = {
        current: Page,
        pageSize: PageSize,
        total: Total,
      }
      await this.getRiskList(this.expanded1,this.listData.find(item=>item.Id==this.expandedRowKeys))
    },
    async getRiskList(expanded, record) {
      console.log("record", record);
      // console.log("expanded", expanded);
      if (expanded) {
        this.record1 = record
        this.expanded1 = expanded 
        const arr = [];
        // 当某一行展开时，关闭其他行
        this.expandedRowKeys = [record.Id];
        const dataList1 = record.child;
        if (dataList1) {
          dataList1.forEach((item) => {
            item.state = record.TaskType;
            arr.push(item);
          });
        }
        this.riskList = arr;
        console.log("this.riskList", this.riskList);

      } else {
        // 当某一行关闭时，清空展开行键列表
        // this.expandedRowKeys = [];
      }
    },
    // action 修改按钮
    async showModal(state, editId, mode, record) {
      if (state === "0") {
        //新建时获取actin ID
        const { data } = await ristCreateAction();
        this.$refs.creatRiskAction.openAction(data);
      } else {
        //编辑
        try {
          // console.log(editId);
          const { data } = await RISKEditActionList({ Id: editId });
          //传值回显
          let allDetails = this.listData.filter((item) => {
            return (
              item.Id === (mode === "DPIA" ? record.DpiaQid : record.RiskId)
            );
          })[0];
          this.$refs.creatRiskAction.openAction(editId, data, 'see')
        
        } catch (error) {
          // 报错信息
          this.$message.error(error);
          console.log(error);
        } finally {
          // 不管成功失败都会执行
          this.listLoading = false;
        }
      }
    },
    //删除action
    async delActions(id) {
      //调接口
      try {
        // 传过来的id直接请求删除api
        await rickActiondel({ Id: id });
        this.succeed();
        this.$message.success(
          this.$t("user.verification-code.required111566110577133")
        );
      } catch (error) {
        this.$message.error(error);
      } finally {
      }
    },
    createActions(precord) {
      // 创建Action
      this.id = precord.Id;
      this.$refs.createAction.open();
    },

  },
}
</script>
<style lang="less" scoped>

.topTitle {
  width: 294px;
  text-align: center;
  color: #5077a5;
  font-weight: 800;
  border-bottom: 2px solid #5077a5;
  padding-bottom: 10px;
}
.review {
  width: 90px;
  margin: 26px 0 0 30px;
}

.review1 {
  width: 125px;
  margin-left: 30px;
}

.text {
  font-size: 16px;
  font-weight: 500;
}

.textBox {
  display: flex;
  width: 50px;
  flex-wrap: wrap;
  align-content: space-between;
  justify-content: center;
}
.textBox1 {
  width: 80px;
  text-align: center;
}

.numTotal {
  width: 64px;
  height: 101px;
  display: flex;
  justify-content: space-between;
  position: absolute;
  left: 170px;
  top: 70px;
}

.numType {
  font-size: 64px;
  color: black;
  cursor: pointer;
}

.numTotal1 {
  width: 101px;
  height: 101px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: absolute;
  left: 200px;
  top: 160px;
}

.numTotal2 {
  width: 85px;
  height: 75px;
  top: 60px;
}

.zhu {
  width: 8px;
  height: 96px;
  background-color: #8EB4DE;
}

.zhu1 {
  height: 64px;
  background-color: #AADC77;
}

.zhu2 {
  height: 64px;
  background-color: #D3D3D3;
}

.echartBox {
  width: 727px;
  height: 100px;
  display: flex;
  margin: 50px 200px;
}

.Pa {
  height: 5px;
  width: 90px;
  background: #ccc;
  position: absolute;
  top: 0px;
  left: 50%;
  cursor: pointer
}

.action-container {
  position: relative;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
}

.action-container:hover .a-tooltip-inner {
  display: block !important;
  position: absolute;
  right: 0;
  top: 0;
}

.button-text {
  font-size: 14px;
  transition: color 0.3s;
  border-radius: 0;
  margin-right: 18px;
  border: 0;
  color: rgba(0, 0, 0, 0.65);
  width: 294px;

  &.active {
    border-bottom: 2px solid #5077a5;
    color: #5077a5;
  }

  &:hover {
    color: #5077a5;
    border-bottom: 2px solid #5077a5;
  }
}

.manipulate {
  position: absolute;
  right: 0;
  margin-top: -24px;
  background: rgba(255, 255, 255, 0.9);
  height: 46px;
  line-height: 49px;
}

.icon {
  font-size: 18px;
  margin: 0 40px;
  width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 50%;
}

.icon:hover {
  background-color: #757575;
  border-radius: 50%;
  text-align: center;
  width: 30px;
  height: 30px;
  line-height: 30px;
}

:deep .ant-pagination {
  text-align: right;
}

.timeline-item-green {
  color: green;
}

.timeline-item-red {
  color: red;
}

.timeline-item-gray {
  color: gray;
}

.ant-card-body {
  padding: 0px !important;
}

</style>